package cn.mybatishelper.builder;

import cn.mybatishelper.entity.CreateFile;
import cn.mybatishelper.entity.database.DatabaseEntity;
import cn.mybatishelper.entity.java.MapperEntity;
import cn.mybatishelper.entity.java.PersistenceEntity;
import cn.mybatishelper.entity.vo.TableToMybatisVo;
import cn.mybatishelper.entity.xml.DefaultXMLEntity;
import cn.mybatishelper.exception.MybatisHelperException;
import cn.mybatishelper.parser.jdbc.AbstractJdbcParser;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang.StringUtils;

import java.util.ArrayList;
import java.util.List;

/**
 * 默认处理器
 * User: GameKing
 */
public class DefaultHandler extends AbstractBuilder implements Handler {

    public DefaultHandler() {
    }

    public DefaultHandler(String extendsClassUrl, AbstractJdbcParser jdbcParser, String rootFilePath, List<TableToMybatisVo> voList) {
        super(extendsClassUrl, jdbcParser, rootFilePath, voList);
    }

    @Override
    public boolean validate() {
        if (!jdbcParser.validateParser()) {
            LOGGER.error("验证有效性时：数据库解析器不合法...");
            return false;
        }
        if (StringUtils.isEmpty(rootFilePath)) {
            LOGGER.error("验证有效性时：classpath为空...");
            return false;
        }
        if (CollectionUtils.isEmpty(voList)) {
            LOGGER.error("验证有效性时：voList为空...");
            return false;
        }
        return true;
    }

    @Override
    public void handle() throws MybatisHelperException {
        buildJdbcParser();
        buildMapperExtendUrl();
        buildRootFilePath();
        buildTableToMybatisVos();

        if (!validate()) {
            LOGGER.error("有效性验证失败，不予执行...");
            return;
        }
        try {
            List<DatabaseEntity> entities = jdbcParser.getJdbcEntitys(this.voList);
            if (CollectionUtils.isNotEmpty(entities)) {
                List<CreateFile> createFiles = new ArrayList<CreateFile>();
                DefaultXMLEntity defaultXMLEntity = new DefaultXMLEntity(rootFilePath);
                createFiles.add(defaultXMLEntity);
                createFiles.add(new PersistenceEntity(rootFilePath));
                createFiles.add(new MapperEntity(rootFilePath, extendsClassUrl, defaultXMLEntity));

                for (DatabaseEntity databaseEntity : entities) {
                    createFile(databaseEntity, createFiles);
                }
            } else {
                LOGGER.info("根据相关参数无法获取任何数据库实体,程序不予执行...");
            }
        } catch (Exception e) {
            LOGGER.error("程序执行出现异常...", e);
        }
    }

    private void createFile(DatabaseEntity databaseEntity, List<CreateFile> createFiles) throws MybatisHelperException {
        if (databaseEntity == null) {
            return;
        }
        for (CreateFile createFile : createFiles) {
            createFile.createFile(databaseEntity);
        }
    }
}
